﻿using System;
using System.Data;
using DGen;

namespace Tab2Sql
{
    /// <summary>
    /// class to help analyse datatypes based on values within datatable.
    /// </summary>
    public class dtHelper
    {
        /// <summary>
        /// Datatype array for datatable.
        /// </summary>
        public DataTypes[] ColTypes;
        /// <summary>
        /// Array recording longest line (in chars) per columnName. Used to generate the VARCHAR(x) values later.
        /// </summary>
        public int[] LongestLines;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">
        /// A <see cref="DataTable"/>
        /// </param>
        public dtHelper(DataTable dt)
        {
            ColTypes = new DataTypes[dt.Columns.Count];
            LongestLines = new int[dt.Columns.Count];

            if (dt == null)
            {
                // oh well
            }
            else
            {
                int iRow = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (iRow == 0)
                        {
                            LongestLines[i] = 0;
                            ColTypes[i] = DataTypes.unknown;
                        }

                        if (dr.Field<string>(i) != null && dr.Field<string>(i) != String.Empty)
                        {
                            LongestLines[i] = Math.Max(dr.Field<string>(i).Length, LongestLines[i]);
                            ColTypes[i] = DTypes.chooseDataType(ColTypes[i], DTypes.GuessMyType(dr.Field<string>(i)));
                        }
                    }
                    iRow++;
                }
            }
        }
    }
}